package _dp_base;

/**
 * 72. 编辑距离
 */
public class No72 {
    private String word1, word2;
    private int[][] cache;

    /**
     * 1. 递归
     */
    public int minDistance1(String word1, String word2) {
        this.word1 = word1;
        this.word2 = word2;
        int n = word1.length();
        int m = word2.length();
        this.cache = new int[n][m];

        return dfs(n - 1, m - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0) return Math.max(i, j) + 1;
        else if (cache[i][j] != 0) return cache[i][j];
        else if (word1.charAt(i) == word2.charAt(j)) return cache[i][j] = dfs(i - 1, j - 1);
        else return cache[i][j] = Math.min(dfs(i - 1, j - 1), Math.min(dfs(i - 1, j), dfs(i, j - 1))) + 1;
    }

    /**
     * 2. 迭代
     */
    public int minDistance2(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();
        int[][] f = new int[n + 1][m + 1];
        for (int j = 0; j < m; j++) {
            f[0][j + 1] = j + 1;
        }
        for (int i = 0; i < n; i++) {
            f[i + 1][0] = i + 1;
            for (int j = 0; j < m; j++) {
                if (word1.charAt(i) == word2.charAt(j)) f[i + 1][j + 1] = f[i][j];
                else f[i + 1][j + 1] = Math.min(f[i][j], Math.min(f[i][j + 1], f[i + 1][j])) + 1;
            }
        }

        return f[n][m];
    }

    /**
     * 4. 一维数组
     */
    public int minDistance4(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();
        int[] f = new int[m + 1];
        for (int j = 0; j < m; j++) {
            f[j + 1] = j + 1;
        }
        for (int i = 0; i < n; i++) {
            int pre = f[0]; // 保留上一个变量
            f[0] = i + 1;
            for (int j = 0; j < m; j++) {
                int temp = f[j + 1];
                if (word1.charAt(i) == word2.charAt(j)) f[j + 1] = pre;
                else f[j + 1] = Math.min(pre, Math.min(f[j + 1], f[j])) + 1;
                pre = temp;
            }
        }

        return f[m];
    }
}
